package kr.co.icebird.temp;

import java.awt.Font;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.imageio.ImageIO;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.NumberFormat;
import jxl.write.WritableCellFormat;
import jxl.write.WritableImage;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import kr.co.icebird.spring3.app.dao.MemberDao;
import kr.co.icebird.spring3.app.dao.MemberDaoImpl;
import kr.co.icebird.spring3.app.model.Member;

public class InsertImageInWork {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws IOException, WriteException {
		// TODO Auto-generated method stub

		try {

			MemberDaoImpl memberService = new MemberDaoImpl();
			WritableWorkbook workbook = Workbook.createWorkbook(new File(
					"c:/temp/firstsheet.xls"));
			WritableSheet sheet = workbook.createSheet("mysheet", 0);
			// WritableFont wfobj = new WritableFont(WritableFont.ARIAL,
			// 12,WritableFont.BOLD);
			// WritableCellFormat cfobj = new WritableCellFormat(wfobj);
			// cfobj.setBackground(Colour.PINK);
			// //cfobj.setWrap(true);

			// Label lblImage = new Label(1, 0, "Image", cfobj);

			// sheet.addCell(lblImage);
			DefaultPieDataset chartDataset = new DefaultPieDataset();
			
			WritableCellFormat numFormat = new WritableCellFormat(
					new NumberFormat("###,###,###,###"));
			int i = 0;
			
			List<Member> rList = memberService.getMemberList();
			for (Member member : rList) {
				int j = 0;
				sheet.addCell(new Label(j++, i, member.getName()));
				sheet.addCell(new Number(j++, i, member.getAge(), numFormat));
				sheet.addCell(new Label(j++, i, member.getAddress()));
				chartDataset.setValue(member.getName(), member.getAge());
				i++;
			}
			JFreeChart chart = ChartFactory.createPieChart(
					"한글테스트", chartDataset, true, true, true);
			chart.getTitle().setFont(new Font("돋음", Font.BOLD, 20));
			
			
			BufferedImage br = chart.createBufferedImage(400, 400);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ImageIO.write( br, "PNG", baos );
			baos.flush();
			byte[] imageInByte = baos.toByteArray();
			baos.close();
			
			WritableImage imgobj = new WritableImage(1, i+3, 5, 15, imageInByte);
			//WritableImage imgobj = new WritableImage(5, 7, 9, 11, new File("c:\\temp\\mypic_new.png"));
			sheet.addImage(imgobj);

			workbook.write();
			workbook.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (WriteException e) {
			e.printStackTrace();
		}
	}
}
